import { ElNotification } from "element-plus";
import { ref, watch, onMounted, shallowRef } from "vue";
import { filter, includes, forEach, uniq, map, find } from "lodash-es";
import { Howl } from "howler";
import AudioMp3 from "@/assets/audio/alarm.mp3";
import { Alarm } from "./types";
import { Ref } from "vue";
import axios from "axios";
import { getDuration } from "@/utils/day";

export default function useNotification(
	alarms: Ref<Alarm[]>,
	running: Ref<boolean>,
	breakTime: Ref<number>
) {
	// @ts-ignore
	const audioConfig = window.$config.audio;

	// @ts-ignore
	const breakTimeConfig = window.$config.breakTime;

	const isTipBreak = ref(false);

	/**
	 * 断线监听
	 */
	watch(breakTime, (val) => {
		if (
			running.value &&
			breakTimeConfig.status &&
			val > Number(breakTimeConfig.value) &&
			!isTipBreak.value
		) {
			isTipBreak.value = true;
			const [time, unit] = getDuration(val * 1000);

			ElNotification({
				title: "提醒",
				message: `已${time}${unit}未接收到报警信息，请及时处理`,
				type: "warning",
				duration: 0,
				onClose: async () => {
					await axios.get("/api/alarms/start");
					isTipBreak.value = false;
				},
			});
		}
	});

	/**
	 * 警告声音
	 */
	const sound = shallowRef<Howl | null>(null);

	/**
	 * 已经警告过的列表
	 */
	const alreadyIdList = ref<number[]>([]);

	/**
	 * 正在警告列表
	 */
	const notificationList = ref<{ id: number; data: any }[]>([]);

	watch(notificationList, (val) => {
		// 声音处理
		if (sound.value && audioConfig.status === 1) {
			if (val.length > 0) {
				if (!sound.value.playing()) {
					sound.value.play();
				}
			} else {
				sound.value?.stop();
			}
		}
	});

	/**
	 * 移出告警列表
	 * @param alarm
	 */
	const onRemove = (id: number) => {
		/**
		 * 告警实例
		 */
		const entity = find(notificationList.value, (item) => {
			return item.id === id;
		});

		/**
		 * 关闭告警
		 */
		if (entity && entity.data) {
			entity.data.close();
		}

		/**
		 * 更新列表
		 */
		notificationList.value = filter(notificationList.value, (item) => {
			return item.id !== id;
		});
	};

	/**
	 * 进入告警列表
	 * @param alarm
	 * @param data
	 */
	const onAdd = (alarm: Alarm, data: any) => {
		notificationList.value = [
			...notificationList.value,
			{
				id: alarm.id,
				data: data,
			},
		];
	};

	/**
	 * 监听ID列表
	 */
	watch(alarms, (val: Alarm[]) => {
		const ids = val.map((item) => item.id);

		// 运行中，需要告警
		if (running.value) {
			// 筛选未告警数据
			const newAlarms = filter(val, (item: Alarm) => {
				return !includes(alreadyIdList.value, item.id);
			});

			// 告警
			forEach(newAlarms, (alarmItem: Alarm, index: number) => {
				setTimeout(() => {
					onNotify(alarmItem);
				}, index * 300);
			});

			// 不告警了的数据
			const needRemove = filter(notificationList.value, (notificationItem) => {
				return !includes(ids, notificationItem.id);
			});

			// 移出正在告警中的列表
			forEach(needRemove, (item: any) => {
				onRemove(item.id);
			});
		}

		// 进入已告警列表
		alreadyIdList.value = uniq([...alreadyIdList.value, ...ids]);
	});

	/**
	 * 报警提醒
	 * @param alarm
	 */
	const onNotify = (_alarm: Alarm) => {
		const notification = ElNotification({
			title: "报警信息",
			message: `${_alarm.channel.name} 发生“${_alarm.description}”，原因为“${_alarm.reason}”，请及时处理`,
			type: "warning",
			duration: 0,
			onClose: () => {
				onRemove(_alarm.id);
			},
		});

		onAdd(_alarm, notification);
	};

	/**
	 * 音频初始化
	 */
	function audioInit() {
		sound.value = new Howl({
			src: [AudioMp3],
			preload: "metadata",
			autoplay: false,
			html5: true,
			loop: true,
		});
	}

	// 断线提醒
	// const noWarnTime = Date.now() - warnLastTime.value;
	// if (noWarnTime > breakTime && isTipBreak.value === false) {
	// 	isTipBreak.value = true;
	// 	ElNotification({
	// 		title: "报警未接收提醒",
	// 		message: "当前已经超过10秒未接收到报警信息，请检查",
	// 		type: "warning",
	// 		duration: 0,
	// 		onClose: () => {
	// 			store.updateWarnLastTime();
	// 			isTipBreak.value = false;
	// 		},
	// 	});
	// }
	// });

	onMounted(() => {
		audioInit();
	});

	return {};
}
